﻿using System.Collections.Generic;
using Entitas;
using System.Linq;
class PlayerCreateMovementCommandSystem : ReactiveSystem<RequestEntity>, ICleanupSystem
{
    CommandContext commandContext;
    PlayerContext playerContext;
    RequestContext requestContext;
    public PlayerCreateMovementCommandSystem(Contexts contexts) : base(contexts.request)
    {
        commandContext = contexts.command;
        playerContext = contexts.player;
        requestContext = contexts.request;
    }



    protected override void Execute(List<RequestEntity> entities)
    {
        if (playerContext.count == 1)
        {
            var player = playerContext.GetEntities().SingleEntity<PlayerEntity>();
            if (player.isAttacking == false)
            {
                foreach (var e in entities)
                {
                    if (ServiceManager.PhysicsService.CastRayToCollider(player,player.position.value, e.movementRequest.direction) == false)
                    {
                        commandContext.CreateEntity().AddMovementCommand(e.movementRequest.Owner, e.movementRequest.direction);
                    }
                   ;
                }
            }
        }
    }

    protected override bool Filter(RequestEntity entity)
    {
        if (playerContext.count == 1)
        {
            var player = playerContext.GetEntities().SingleEntity<PlayerEntity>();
            if (entity.hasMovementRequest)
            {
                if (entity.movementRequest.Owner == player.name.value)
                    return true;
                else return false;
            }
            else return false;
        }
        else return false;
    }

    protected override ICollector<RequestEntity> GetTrigger(IContext<RequestEntity> context)
    {
        return context.CreateCollector(RequestMatcher.MovementRequest.Added());
    }

    public void Cleanup()
    {
        if (playerContext.count == 1)
        {
            var player = playerContext.GetEntities().SingleEntity<PlayerEntity>();
            foreach (var e in requestContext.GetEntities().Where(x => x.hasMovementRequest && x.movementRequest.Owner ==player.name.value))
            {
                e.Destroy();
            }
        }
    }
}
